import Request from 'utils/request';

import SystemUtil from 'utils/systemUtil';

import GoodsDetail from 'models/goods/goodsDetail';
import GoodsDetailHistory from 'models/goods/goodsDetailHistory';
import GoodsDetailEvaluate from 'models/goods/goodsDetailEvaluate';
import ShopGoodsModel from 'models/shopMall/shopGoodsModel';

export default class GoodsApi {
  static getGoodsDetail(id) {
    const apiName = 'api/wehcatshop/goodsInfo';

    return Request.post(apiName, {
      goodsDefId: id
    }).then(res => {
      let goodsDetail = res.data;
      goodsDetail = new GoodsDetail(goodsDetail);
      return goodsDetail;
    });
  }

  static addGoodsDetailHistory(id) {
    const apiName = 'api/wehcatshop/goodsBrowsingHistoryAdd';

    return Request.post(apiName, {
      goodsDefId: id
    }).then(res => {
      return res.msg;
    });
  }

  static getGoodsDetailHistory(id) {
    const apiName = 'api/wehcatshop/goodsBrowsingHistory';

    let postData = {
      goodsDefId: id,
      limit: 10,
      page: 1
    };

    return Request.post(apiName, postData).then(res => {
      let historys = res.data;
      let historyList = [];
      for (let i = 0; i < historys.length; i++) {
        let history = historys[i];
        history = new GoodsDetailHistory(history, res.systemTime);
        historyList.push(history);
      }

      return historyList;
    });
  }

  static getGoodsDetailEvaluate(id, pagination) {
    const apiName = 'api/wehcatshop/goodsAppraiseList';

    let postData = {
      goodsDefId: id,
      limit: pagination.pageSize,
      page: pagination.currentPage
    };

    return Request.post(apiName, postData).then(res => {
      let evaluates = res.data;
      if (SystemUtil.isEmpty(evaluates)) {
        evaluates = [];
      }
      let evaluateList = [];
      for (let i = 0; i < evaluates.length; i++) {
        let evaluate = evaluates[i];
        evaluate = new GoodsDetailEvaluate(evaluate);
        evaluateList.push(evaluate);
      }

      pagination.totalCount = res.rows;
      return evaluateList;
    });
  }

  static getGoodsModelData(defId, buyRecord) {
    const apiName = 'api/wehcatshop/getGoodsModelByDefId';

    return Request.post(apiName, {
      goodsDefId: defId
    }).then(res => {
      let goodsModelData = res.data;
      goodsModelData = new ShopGoodsModel(goodsModelData, buyRecord);
      return goodsModelData;
    });
  }
}
